import Cookies from 'js-cookie'

// 根域名
const ROOT_DOMAIN = { domain: '.ybsjyyn.com' }

// 获取url上的参数
export const getURLParameters = (url) => {
  const query = url.match(/([^?=&]+)(=([^&]*))/g) || []
  return query.reduce(
    (a, v) => (
      (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
    ),
    {},
  )
}

// 退出登录清除所有cookie
export function removeAllCookie() {
  let keys = document.cookie.match(/[^ =;]+(?==)/g) || []
  keys = new Set([...keys])
  keys.forEach((item) => {
    Cookies.remove(item)
    Cookies.remove(item, ROOT_DOMAIN)
  })
}

// 根据环境变量标识生成跳转地址
export function buildUrl() {
  const url = `${import.meta.env.VITE_APP_LOGIN_URL}?redirect_uri=`
  const redirectUrl = `${encodeURIComponent(
    location.origin +
    location.pathname +
    location.hash +
    location.search,
  )}`
  return url + redirectUrl
}

// 清除本地cookie再跳转登录页面
export function turnToLogin() {
  const url = buildUrl()
  removeAllCookie()
  window.location.replace(url)
}

// 获取jwt
export function getToken() {
  const jwt = Cookies.get('jwt')
  if (!jwt) {
    return false
  }
  return jwt
}
